<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
    <button id="button1">首页</button>
    <button id="button2">商城</button>
    <button id="button3">我的</button>

    <script>
      /*方法一*/

      const _wr = function (type) {
        const orig = window.history[type] || history.pushState;
        return function (...rest) {
          const rv = orig.apply(this, arguments);
          const e = new Event(type);
          e.arguments = arguments;
          window.dispatchEvent(e);
          return rv;
        };
      };
      history.pushState = _wr('pushState');
      history.replaceState = _wr('replaceState');

      const button1 = document.querySelector('#button1');
      const button2 = document.querySelector('#button2');
      const button3 = document.querySelector('#button3');

      button1.onclick = function () {
        history.pushState({ state: 1 }, null, './home');
      };

      button2.onclick = function () {
        history.pushState({ state: 2 }, null, './my-router.html/shop');
      };

      button3.onclick = function () {
        history.replaceState({ state: 3 }, null, './my-router.html/mine');
      };

      window.addEventListener('pushState', function (e) {
        console.log('pushState===', e.arguments);
      });
      window.addEventListener('replaceState', function (e) {
        console.log('replaceState===', e.arguments);
      });

      /*方法二*/
      // (function (history) {
      //   const pushState = history.pushState;
      //   history.pushState = function (state) {
      //     if (typeof history.onpushstate === 'function') {
      //       history.onpushstate({ state: state });
      //     }
      //     return pushState.apply(history, arguments);
      //   };
      // })(window.history);

      // //设置其方法和popstate相同即可
      // history.onpushstate = function (event) {
      //   console.log('event', event);
      //   // alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state));
      // };
    </script>
  </body>
</html>
